package com.alibaba.citrus.cr.unified.inventory.utils;

import com.alibaba.citrus.cr.common.util.SpringContextUtil;
import com.alibaba.citrus.cr.unified.inventory.common.SetOrderTag;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIdsAllRequest;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByIdsAllResponse;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crb2btradecenter.sdo.OrderSDO;
import com.epoch.app.crunifiedinventory.model.dto.QueryCargoZoneById2Request;
import com.epoch.app.crunifiedinventory.model.dto.WarehouseInfoDTO;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Chen.mu
 * 2023/6/13
 **/
public class OrderOutCodeAssmeble {
    public static BaseDataService baseDataService;
    private static CrUnifiedInventoryService crUnifiedInventoryService;
    private static Log log = Log.getLogger(OrderOutCodeAssmeble.class);

    static {
        baseDataService = SpringContextUtil.getBean(BaseDataService.class);
        crUnifiedInventoryService = SpringContextUtil.getBean(CrUnifiedInventoryService.class);
    }

    /**
     * 拼接订单主单外部编码
     */
    public static void assembleOutCode(OrderSDO orderSDO) {
        // 业态有值时不进行覆盖，防止业中的订单业态被覆盖
        if (Objects.isNull(orderSDO.getBusinessType())) {
            String businessType = StringUtils.isNotBlank(orderSDO.getProductGroupCode()) ? orderSDO.getProductGroupCode().trim() : "11";
            orderSDO.setBusinessType(Integer.valueOf(businessType));
        }
        getOrganization(orderSDO);
        getWarehouseInfo(orderSDO);
    }

    /**
     * 拼接订单明细的外部编码
     */
    public static void assembleOrderLineOutCode(OrderSDO orderSDO) {
        getWarehouseInfo(orderSDO);
    }

    private static void getOrganization(OrderSDO orderSDO) {
        //查询销售组织信息
        String bisUnitCode = orderSDO.getBisUnitCode();
        String saleChannelCode = orderSDO.getSaleChannelCode();
        String departmentCode = orderSDO.getDepartmentCode();
        String organizationCode = orderSDO.getOrganizationCode();
        BaselineGetOrganizationByIdsAllRequest idQueryRequest = new BaselineGetOrganizationByIdsAllRequest();
        idQueryRequest.setIds(Arrays.asList(bisUnitCode, saleChannelCode, departmentCode, organizationCode));
        BaselineGetOrganizationByIdsAllResponse result = baseDataService.baselineGetOrganizationByIdsAll(idQueryRequest);
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())) {
            Map<String, OrganizationSDO> organizationSDOMap = result.getResult().stream().collect(Collectors.toMap(x -> x.getId(), o -> o));
              log.info("OrderOutCodeAssmeble_getOrganization_orderId:{},map:{}",orderSDO.getOrderBizId(), JSON.toJSON(organizationSDOMap));
                if (Objects.isNull(orderSDO.getBusinessUnitOutCode()) && organizationSDOMap.get(orderSDO.getOrganizationCode()) != null) {
                    orderSDO.setBusinessUnitOutCode(organizationSDOMap.get(orderSDO.getOrganizationCode()).getOutCode());
                }
                if (Objects.isNull(orderSDO.getSaleChannelOutCode()) && organizationSDOMap.get(orderSDO.getSaleChannelCode()) != null) {
                    orderSDO.setSaleChannelOutCode(organizationSDOMap.get(orderSDO.getSaleChannelCode()).getOutCode());
                }
                if (Objects.isNull(orderSDO.getOrganizationOutCode()) && organizationSDOMap.get(orderSDO.getOrganizationCode()) != null) {
                    orderSDO.setOrganizationOutCode(organizationSDOMap.get(orderSDO.getOrganizationCode()).getOutCode());
                }
                if (Objects.isNull(orderSDO.getDepartmentOutCode()) && organizationSDOMap.get(orderSDO.getDepartmentCode()) != null) {
                    orderSDO.setDepartmentOutCode(organizationSDOMap.get(orderSDO.getDepartmentCode()).getOutCode());
                }
            log.info("OrderOutCodeAssmeble_getOrganization_after:{}",JSON.toJSON(orderSDO));
        }
    }

    private static OrderSDO getWarehouseInfo(OrderSDO orderSDO) {
        //查询发货逻辑仓信息
        String warehouseCode = orderSDO.getWareHouseCode();
        if (StringUtils.isNotBlank(warehouseCode)) {
            QueryCargoZoneById2Request byIdRequest = new QueryCargoZoneById2Request();
            byIdRequest.setCargoZoneIdList(Arrays.asList(warehouseCode));
            Result<List<WarehouseInfoDTO>> warehouseInfoResult = crUnifiedInventoryService.queryCargoZoneById2(byIdRequest);
            if (warehouseInfoResult!=null&&CollectionUtils.isNotEmpty(warehouseInfoResult.getResult())) {
                WarehouseInfoDTO warehouseInfoDTO = warehouseInfoResult.getResult().get(0);
                if (Objects.nonNull(warehouseInfoDTO)) {
                    orderSDO.setWareHouseName(warehouseInfoDTO.getName());
                    orderSDO.setWareHouseCode(warehouseInfoDTO.getId());
                    orderSDO.setWareHouseOutCode(warehouseInfoDTO.getCode());
                    if (CollectionUtils.isNotEmpty(orderSDO.getOrderLineSDOS())) {
                        orderSDO.getOrderLineSDOS().stream().forEach(
                                x -> {
                                    if (SetOrderTag.EXCHANGE.equals(orderSDO.getOrderTag())) {
                                        if (SetOrderTag.RETURN.equals(x.getOrderLineTag())) {
                                            x.setShippingWarehouseOutCode("");
                                            x.setShippingWarehouseName("");
                                            x.setShippingWarehouseCode("");
                                            x.setDeliveryFactoryCode("");
                                            x.setStockCode("");
                                            return;
                                        }
                                    }
                                    x.setShippingWarehouseOutCode(warehouseInfoDTO.getCode());
                                    x.setShippingWarehouseName(warehouseInfoDTO.getName());
                                    x.setShippingWarehouseCode(warehouseInfoDTO.getId());
                                    x.setDeliveryFactoryCode(warehouseInfoDTO.getSapFactoryCode());
                                    x.setStockCode(warehouseInfoDTO.getWarehouseCode());
                                }
                        );
                    }
                }
            }
        }

        String receiveWarehouseCode = orderSDO.getReceiveWareHouseCode();
        if (StringUtils.isNotBlank(receiveWarehouseCode)) {
            QueryCargoZoneById2Request byIdRequest = new QueryCargoZoneById2Request();
            byIdRequest.setCargoZoneIdList(Arrays.asList(receiveWarehouseCode));
            Result<List<WarehouseInfoDTO>> warehouseInfoResult = crUnifiedInventoryService.queryCargoZoneById2(byIdRequest);
            if (CollectionUtils.isNotEmpty(warehouseInfoResult.getResult())) {
                WarehouseInfoDTO warehouseInfoDTO = warehouseInfoResult.getResult().get(0);
                if (Objects.nonNull(warehouseInfoDTO)) {
                    orderSDO.setReceiveWareHouseCode(warehouseInfoDTO.getId());
                    orderSDO.setReceiveWareHouseName(warehouseInfoDTO.getName());
                    orderSDO.setReceiveWareHouseOutCode(warehouseInfoDTO.getCode());
                    if (CollectionUtils.isNotEmpty(orderSDO.getOrderLineSDOS())) {
                        orderSDO.getOrderLineSDOS().stream().forEach(
                                x -> {
                                    if (SetOrderTag.EXCHANGE.equals(orderSDO.getOrderTag())) {
                                        if (SetOrderTag.EXCHANGE.equals(x.getOrderLineTag())) {
                                            x.setReceiveWarehouseCode("");
                                            x.setReceiveWarehouseName("");
                                            x.setReceiveWarehouseOutCode("");
                                            x.setReceiveFactoryCode("");
                                            x.setReceiveStockCode("");
                                            return;
                                        }
                                    }
                                    x.setReceiveWarehouseCode(warehouseInfoDTO.getId());
                                    x.setReceiveWarehouseName(warehouseInfoDTO.getName());
                                    x.setReceiveWarehouseOutCode(warehouseInfoDTO.getCode());
                                    x.setReceiveFactoryCode(warehouseInfoDTO.getSapFactoryCode());
                                    x.setReceiveStockCode(warehouseInfoDTO.getWarehouseCode());
                                }
                        );
                    }
                }
            }
        }
        return orderSDO;
    }
}
